package com.example.demo.thread;

import org.apache.tomcat.util.threads.ThreadPoolExecutor;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 线程池饱和策略
 * @Author: xiatian
 * @CreateTime: 2021/8/20
 * @Company: kangxu
 */
public class ThreadPoolSaturationPolicyDemo {
    public static void policy(RejectedExecutionHandler handler) {
        //基本线程2个，最大线程数为3，工作队列容量为5
        ThreadPoolExecutor exec = new ThreadPoolExecutor(2, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(5));
        if (handler != null) {
            //设置饱和策略
            exec.setRejectedExecutionHandler(handler);
        }
        for (int i = 0; i < 10; i++) {
            //提交任务
            exec.submit(new Task());
        }
        exec.shutdown();
    }

    public static void main(String[] args) {
        //直接抛出异常，组织系统正常运行
        //policy(new ThreadPoolExecutor.AbortPolicy());
        //任务交给调用者，运行当前被丢弃的任务
        policy(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
        //丢弃无法处理的任务，不予处理
        //policy(new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy());
        //拒绝最老的请求，也就是即将被执行的一个任务，并尝试再次提交当前任务
        //policy(new java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy());
    }

    static class Task implements Runnable {

        private static int count = 0;
        private int id = 0;//任务标识

        public Task() {
            id = ++count;
        }

        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(2);//休眠3秒
            } catch (InterruptedException e) {
                System.err.println("线程被中断" + e.getMessage());
            }
            System.out.println(" 任务：" + id + "\t 工作线程: " + Thread.currentThread().getName() + " 执行完毕");
        }

    }
}
